package jframe.model;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.IDataLoader;
import ulric.kit.CollectionKit;
import ulric.kit.SQLKit;

import java.util.*;

/**
 * 对友情链接的CRUD不需要操作缓存
 * <p/>
 * 只是在最终首页上展示list的时候cache一下即可，比如10分钟失效，这个数据不重要，做的更新晚一点体现出来无伤大雅
 * 实在是着急，可以单独做一个util页面，清理缓存用的
 */
public class Blogroll extends Model<Blogroll> {

    private static final long serialVersionUID = 3521964237176253650L;
    public static final Blogroll dao = new Blogroll();

    public static void save(String title, String url, int weight) {
        Blogroll blogroll = dao.findFirst("select id,title,url,weight from blogroll where url = ?", url);
        if (blogroll == null) {
            boolean success = new Blogroll().set("title", title).set("url", url).set("weight", weight).save();
            if (success) {
                CacheKit.remove(Blogroll.class.getSimpleName(), "ids");
            }
        } else {
            boolean success = blogroll.set("title", title).set("weight", weight).update();
            if (success) {
                CacheKit.remove(Blogroll.class.getSimpleName(), blogroll.getLong("id"));
            }
        }
    }

    public static List<Blogroll> list() {
        List<Long> ids = listIds();
        List<Blogroll> list = listRecords(ids);
        return list;
    }

    private static List<Blogroll> listRecords(List<Long> ids) {
        if (CollectionKit.isEmpty(ids)) {
            return Collections.emptyList();
        }

        int size = ids.size();
        List<Blogroll> ret = new ArrayList<Blogroll>(size);
        for (int i = 0; i < size; i++) {
            ret.add(null);
        }
        Map<Integer, Long> index_id = new HashMap<Integer, Long>();

        String cacheName = Blogroll.class.getSimpleName();

        for (int i = 0; i < size; i++) {
            Long id = ids.get(i);
            Blogroll o = CacheKit.get(cacheName, id);
            ret.set(i, o);
            if (o == null) {
                index_id.put(i, id);
            }
        }

        int notInCacheIdsSize = index_id.size();
        if (notInCacheIdsSize > 0) {
            String sql = "select id,title,url,weight from blogroll where id in (" + SQLKit.joinQuestionMark(notInCacheIdsSize) + ")";
            List<Blogroll> blogrolls = dao.find(sql, index_id.values().toArray());
            for (Blogroll blogroll : blogrolls) {
                CacheKit.put(cacheName, blogroll.getLong("id"), blogroll);
            }
        } else {
            return ret;
        }

        for (Map.Entry<Integer, Long> entry : index_id.entrySet()) {
            ret.set(entry.getKey(), oneRecord(entry.getValue()));
        }

        return ret;
    }

    public static Blogroll oneRecord(final Long id) {
        Blogroll blogroll = CacheKit.get(Blogroll.class.getSimpleName(), id, new IDataLoader() {
            @Override
            public Object load() {
                return dao.findById(id);
            }
        });
        return blogroll;
    }

    public static List<Long> listIds() {
        List<Long> ids = CacheKit.get(Blogroll.class.getSimpleName(), "ids", new IDataLoader() {
            @Override
            public Object load() {
                String sql = "select id from blogroll order by weight desc";
                return Db.query(sql);
            }
        });
        return ids;
    }

}